<template>
  <div class="app-container">
    <el-form ref="queryFormRef" :inline="true" :model="queryParams" class="demo-form-inline"
      v-hasPermi="['md:product:query']">
      <el-form-item label="系列" prop="series">
        <el-select v-model="queryParams.series" size="small" clearable filterable placeholder="请选择产品系列">
          <el-option
            v-for="item in dict.type.sys_product_series"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
        <!-- <el-input v-model.trim="queryParams.series" size="small" clearable :minlength="100"
          placeholder="请输入系列"></el-input> -->
      </el-form-item>
      <el-form-item label="产品名称" prop="productName">
        <el-input v-model.trim="queryParams.productName" size="small" clearable :minlength="100"
          placeholder="请输入产品名称"></el-input>
      </el-form-item>
      <el-form-item label="产品型号" prop="productCode">
        <el-input v-model.trim="queryParams.productCode" size="small" clearable :minlength="100"
          placeholder="请输入产品型号"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="searchHandler">查询</el-button>
        <el-button icon="el-icon-refresh-right" size="mini" @click="resetHandler">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="20">
      <el-col :span="12">
        <div class="grid-content bg-purple">
          <el-button plain type="primary" size="mini" icon="el-icon-plus" v-hasPermi="['md:product:add']"
            @click="openDialog(null)">增加</el-button>
          <!--          <el-button plain type="warning" size="mini" icon="el-icon-download" v-hasPermi="['sa:report:export']" @click="exportHandler">导出</el-button>-->
        </div>
      </el-col>
      <el-col :span="12">
        <div class="grid-content bg-purple"></div>
      </el-col>
    </el-row>

    <el-table ref="tableRef" :data="tableData" v-loading="loading" highlight-current-row max-height="680"
      v-horizontal-scroll="'auto'" style="width: 100%;margin-top: 10px;">
      <el-table-column type="index" width="50" align="center" label="序号">
        <template slot-scope="scope">
          <span>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column property="series" label="系列" align="center" width="80"/>
      <el-table-column property="productName" label="产品名称" align="center" width="100"/>
      <el-table-column property="productCode" label="产品型号" align="center" width="80" />
      <el-table-column property="description" label="职教简介" align="center" min-width="320" />
      <el-table-column property="descriptionHigh" label="高教简介" align="center" min-width="320" />
      <el-table-column property="image" label="定妆照" align="center" width="180">
        <template slot-scope="scope">
          <el-image lazy style="width: 160px; height: auto;" fit="contain" :src="env + scope.row.image"
            @click="handlePictureCardPreview({ url: scope.row.image })">
            <div slot="error" class="image-slot">
              <i class="el-icon-picture-outline"></i>
            </div>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column property="technicalPerson" label="技术负责人" align="center" width="100"/>
      <el-table-column property="academyPerson" label="研究院负责人" align="center" width="100" />
      <el-table-column property="remark" label="备注" align="center" />
      <el-table-column property="createBy" label="创建人" align="center" width="80" />
      <el-table-column property="createTime" label="创建时间" align="center" sortable width="100"/>
      <el-table-column label="操作" align="center"
        v-if="$auth.hasPermi('md:product:edit') || $auth.hasPermi('md:product:remove')">
        <template slot-scope="scope">
          <el-button type="text" icon="el-icon-edit" v-hasPermi="['md:product:edit']"
            @click="openDialog(scope.row)">修改</el-button>
          <el-popconfirm confirm-button-text="是" cancel-button-text="否" title="确定删除吗？"
            @confirm="deleteHandler(scope.row)">
            <el-button slot="reference" icon="el-icon-delete" v-hasPermi="['md:product:remove']"
              type="text" style="margin-left: 10px">删除</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <el-dialog :title="dialogTitle === 1 ? '新增' : '修改'" :visible.sync="dialogVisible" width="700px"
      :close-on-click-modal="false" :fullscreen="device =='mobile'">
      <el-form :model="form" :rules="rules" ref="formRef" class="demo-form" label-width="100px" :label-position="device =='mobile' ? 'top' : 'right'">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="系列" prop="series">
              <el-select v-model="form.series" filterable placeholder="请选择产品系列" style="width: 100%;">
                <el-option
                  v-for="item in dict.type.sys_product_series"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
              <!-- <el-input v-model.trim="form.series" clearable placeholder="请输入产品系列" :maxlength="50" :autosize="{ minRows: 2 }" /> -->
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="产品名称" prop="productName">
              <el-input v-model.trim="form.productName" clearable placeholder="请输入产品名称" :maxlength="50" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="产品型号" prop="productCode">
              <el-input v-model.trim="form.productCode" clearable placeholder="请输入产品型号" :maxlength="50" :autosize="{ minRows: 2 }" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="技术负责人" prop="technicalPerson">
              <el-input v-model.trim="form.technicalPerson" :maxlength="10" placeholder="请输入技术负责人" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="研究院负责人" prop="academyPerson">
              <el-input v-model.trim="form.academyPerson" :maxlength="10" placeholder="请输入研究院负责人" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="显示排序" prop="orderNum">
              <el-input-number v-model.trim="form.orderNum" :min="0" :step="1" step-strictly style="width: 100%;" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="职教简介" prop="description">
              <el-input v-model.trim="form.description" type="textarea" :maxlength="2000" placeholder="请输入产品职教简介"
                :autosize="{ minRows: 2 }" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="高教简介" prop="descriptionHigh">
              <el-input v-model.trim="form.descriptionHigh" type="textarea" :maxlength="2000" placeholder="请输入产品高教简介"
                :autosize="{ minRows: 2 }" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model.trim="form.remark" type="textarea" :maxlength="250" placeholder="请输入备注"
                :autosize="{ minRows: 2 }" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="定妆照" prop="image">
              <el-upload ref="uploadImg" action="" :file-list="fileList" :auto-upload="false"
                :limit="1" :on-preview="handlePictureCardPreview" :multiple="false"
                :on-change="handlePictureChange" :show-file-list="false">
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件</div>
              </el-upload>
              <el-image v-if="form.image" style="width: 100px; height: auto;object-fit: contain;" :src="env + form.image"
                  @click="handlePictureCardPreview({ url: form.image})"
              >
                <div slot="error" class="image-slot">
                  <i class="el-icon-picture-outline"></i>
                </div>
              </el-image>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm('formRef')">提交</el-button>
        <el-button @click="dialogVisible = false">取消</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="imgDialogVisible" width="800px" :fullscreen="device =='mobile'">
      <img width="100%" height="auto" style="object-fit: contain;" :src="imgDialogUrl" alt="">
    </el-dialog>
  </div>
</template>
<script>
import { addDataApi, deleteDataApi, getDataListApi, updateDataApi, uploadImgApi } from "@/api/crm/md/product";
import { getDataListApi as getAllProjectListApi } from "@/api/crm/md/project";
import ProvinceData from '@/views/crm/data/province.json'
import { getUserProfile } from "@/api/system/user";
import { mapGetters } from 'vuex'

export default {
  name: 'ProductView',
  dicts: ['sys_product_series'],
  data() {
    return {
      // 记录上一次打开弹窗是修改or增加
      // null 增加
      // 非null 修改
      formId: null,
      imgDialogUrl: "",// 预览图链接
      fileList: [],
      env: process.env.VUE_APP_STATIC_API || '',
      srcList: [], // 预览图数组
      file: {
        url: null
      }, // 用户上传的图片
      // 上传的图片服务器地址
      // uploadImgUrl: process.env.VUE_APP_BASE_API + "/common/upload",
      // // 预览图片的链接
      // image: '',
      // 预览图片的弹框
      imgDialogVisible: false,
      // 项目日期
      projectDate: [],
      pickerOptions: {
        disabledDate(time) {
          // 禁止选择今天及今天之后的日期
          return time.getTime() > Date.now();
        }
      },
      // 加载动画
      loading: true,
      // 省份数据
      provinceList: [],
      // 弹框标题 1是增加 其他是修改
      dialogTitle: 1,
      // 弹框显示
      dialogVisible: false,
      // 新增和修改参数
      form: {
        orderNum: null, // 显示排序
        technicalPerson: "", // 技术负责人
        academyPerson: "", // 研究院负责人
        createBy: "", // 创建人
        createTime: "", // 创建时间
        id: null,
        remark: "", // 备注
        updateBy: "",
        updateTime: "",
        productName: "", // 产品名称
        productCode: "", // 产品型号
        series: "", // 产品系列
        description: "", // 职教简介
        descriptionHigh: "", // 高教简介
        image: "", // 预览图片的链接
      },
      // 重点客户下拉数据
      isImportantList: [
        {
          value: 0,
          label: '普通客户'
        },
        {
          value: 1,
          label: '重点客户'
        }
      ],
      // 表单的校验规则
      rules: {
        province: [
          { required: true, message: '请选择省份', trigger: 'change' }
        ],
        orderNum: [
          { required: true, message: '请输入显示排序', trigger: 'blur' }
        ],
        productName: [
          { required: true, message: '请输入产品名称', trigger: 'blur' }
        ],
        productCode: [
          { required: true, message: '请输入产品型号', trigger: 'blur' }
        ],
        series: [
          { required: true, message: '请输入产品系列', trigger: 'change' }
        ],
      },
      // 表格数据
      tableData: [],
      // 总数条数
      total: 0,
      // 查询参数
      queryParams: {
        productName: "", // 产品名称
        productCode: "", // 产品型号
        series: "", // 产品系列
        pageNum: 1,
        pageSize: 10,
      },
      // 用户信息
      user: {},
      roleGroup: {},
      postGroup: {},
      // 项目数据
      projectList: [],
    }
  },
  computed: {
    ...mapGetters([
      'device'
    ]),
  },
  watch: {
    projectDate: {
      handler(newV) {
        if (newV) {
          this.queryParams.startDate = newV[0] ?? ''
          this.queryParams.endDate = newV[1] ?? ''
        } else {
          this.queryParams.startDate = ''
          this.queryParams.endDate = ''
        }
      },
    },
    'form.isImportant': {
      handler(newV) {
        if (newV !== 1) {
          this.form.basis = null
        }
      }
    },
  },
  created() {
    this.provinceList = ProvinceData
    this.getList()
    this.getUserinfo()
    this.getAllProjectList()
  },
  activated() {
    this.getList()
  },
  methods: {
    // 删除图片的回调
    // handleRemove(file, fileList) {
    //   this.fileList = []
    //   this.form.image = ""
    // },
    // 图片预览弹框
    handlePictureCardPreview(file) {
      this.imgDialogUrl = this.env + file.url
      this.imgDialogVisible = true;
    },
    // 手动上传图片
    async submitUpload() {
      const formData = new FormData()
      formData.append('file', this.file.raw)
      const res = await uploadImgApi(formData)
      if (res.code === 200) {
        this.$message({
          message: "上传成功",
          type: 'success'
        });
        this.form.image = res.fileName
        this.fileList = []
      }
    },
    // 上传图片改变的回调
    handlePictureChange(file) {
      this.file = file
      this.submitUpload()

      // imageToBase64(file.raw)
      // .then((url) => {
      //   this.image = url;
      // })
      // .catch((err) => {console.log(err)})
    },
    // 查询全部项目
    getAllProjectList() {
      getAllProjectListApi().then((res) => {
        this.projectList = res.rows ?? []
      })
    },
    // 选择重点的回调
    changePropertyHandler(val) {
      if (val === 0) {
        this.form.basis = null
      }
    },
    // 获取根据list中的value返回label
    getListValue(data, list, value = 'value') {
      let label = ''
      list.map((item) => {
        if (+item[value] === +data) {
          label = item.label
        }
      })
      return label
    },
    // 获取用户信息
    getUserinfo() {
      getUserProfile().then(response => {
        this.user = response.data;
        this.roleGroup = response.roleGroup;
        this.postGroup = response.postGroup;
      });
    },
    // 获取数据
    async getList() {
      this.loading = true
      const res = await getDataListApi(this.queryParams)
      if (res.code === 200) {
        // const list = (res.rows ?? []).map((item) => {
        //   return {
        //     ...item,
        //     image: process.env.VUE_APP_BASE_API + item.image
        //   }
        // })
        this.tableData = res.rows ?? []
        this.total = res.total
      }
      this.loading = false
    },
    // 搜索的回调
    searchHandler() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    // 删除的回调
    async deleteHandler(row) {
      const res = await deleteDataApi({
        id: row.id
      })
      if (res.code === 200) {
        this.$message({
          message: res.msg,
          type: 'success'
        });
        this.getList()
        this.dialogVisible = false
      } else {
        this.$message({
          message: res.msg,
          type: 'error'
        });
      }
    },
    // 打开弹窗
    openDialog(row) {
      if (row) {
        this.formId = row.id
        this.form = { ...row }
        this.dialogTitle = 2
      } else {
        if(this.formId) {
          this.form = { ...this.$options.data().form }
        }
        this.formId = null
        this.dialogTitle = 1
      }
      this.fileList = []
      this.dialogVisible = true
      // this.resetForm('formRef')
      this.$nextTick(()=>{
        this.$refs['formRef'].clearValidate();
        // this.resetForm('formRef')
      })
    },
    // 导出的回调
    async exportHandler() {
      this.download('crm/product/export', {
        ...this.queryParams,
        userId: this.user.userId,
        deptId: this.user.deptId,
      }, `products_${new Date().getTime()}.xlsx`)
    },
    // 表单提交
    async submitForm(formName) {

      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.dialogTitle === 1) {
            this.addDataHandler()
          } else {
            this.updateDataHandler()
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 增加数据的回调
    async addDataHandler() {
      const payload = {
        ...this.form,
        deptId: this.user.deptId,
        userId: this.user.userId,
        createBy: this.user.nickName,
        updateBy: this.user.nickName,
      }
      const res = await addDataApi(payload)
      if (res.code === 200) {
        this.$message({
          message: res.msg,
          type: 'success'
        });
        this.getList()
        this.formId = -1
        this.dialogVisible = false
        this.$refs.formRef.resetFields()
      } else {
        this.$message({
          message: res.msg,
          type: 'error'
        });
      }
    },
    // 修改数据的回调
    async updateDataHandler() {
      const payload = {
        ...this.form,
        updateBy: this.user.nickName,
      }
      const res = await updateDataApi(payload)
      if (res.code === 200) {
        this.$message({
          message: res.msg,
          type: 'success'
        });
        this.getList()
        this.dialogVisible = false
      } else {
        this.$message({
          message: res.msg,
          type: 'error'
        });
      }
    },
    // 重置表单
    resetForm(formName) {
      if (this.$refs[formName]) {
        this.$refs[formName].resetFields();
      }
    },
    // 重置的回调
    resetHandler() {
      this.projectDate = []
      this.resetForm('queryFormRef')
    },
  },
}
</script>
<style scoped lang="scss"></style>
